﻿using System;
using UnityEngine;

namespace Intersection111
{

    public class Rectangle
    {
        //public int x;
        //public int y;
        //public int width;
        //public int height;

        public Vector3[] Corners = new Vector3[4];

    }
    public struct Circle1
    {
        public Vector2 Center;
        public float Radius;
        public float RadiusSquare; // 半径平方

        public Circle1(Vector2 center, float radius)
        {
            Center = center;
            Radius = radius;
            RadiusSquare = radius * radius;
        }

        //public AABB GetAABB()
        //{
        //    AABB aabb = new AABB();
        //    aabb.XMin = Center.x - Radius;
        //    aabb.XMax = Center.x + Radius;
        //    aabb.YMin = Center.y - Radius;
        //    aabb.YMax = Center.y + Radius;
        //    return aabb;
        //}
    }

    public class RectangleMono : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start()
        {
            var rect1 = new Rectangle1(1, 1, new Vector2(1, 1), Vector2.up);

            var c1 = new Circle1()
            {
                Center = new Vector3(2, 2, 0),
                Radius = 1
            };

            var time1 = DateTime.Now;

            int cnt = 0;

            for (int i = 0; i < 100000; i++)
            {
                var result = CheckCircleInRect(c1, rect1);
                if (result == false)
                {
                    cnt++;
                }
            }

            var time2 = DateTime.Now;

            Debug.LogError(cnt);
            Debug.LogError($"圆形和矩形检测10W次：{(time2 - time1).TotalMilliseconds}");

        }

        // Update is called once per frame
        void Update()
        {

        }

        public static bool CheckCircleInRect(Circle1 c, Rectangle1 r)
        {
            //if (!CheckAABB(c.GetAABB(), r.GetAABB()))
            //{
            //    return false;
            //}
            // c.Center转化到以r.Center为原点
            Vector2 v = c.Center - r.Center;
            // 转换到r的局部坐标
            float circleLocalPosX = v.x * r.XAxis.x + v.y * r.XAxis.y;
            float circleLocalPosY = v.x * r.YAxis.x + v.y * r.YAxis.y;
            Vector2 circleLocalPos = new Vector2(circleLocalPosX, circleLocalPosY);
            float closestX = Mathf.Clamp(circleLocalPos.x, -r.HalfWidth, r.HalfWidth);
            float closestY = Mathf.Clamp(circleLocalPos.y, -r.HalfHeight, r.HalfHeight);
            Vector2 closest = new Vector2(closestX, closestY);
            return (circleLocalPos - closest).SqrMagnitude() <= c.Radius * c.Radius;
        }

    }
}